const express = require('express');
const router = express.Router();
const { authenticateToken, requireAdmin } = require('../middleware/auth');
const { body } = require('express-validator');
const { handleValidationErrors } = require('../middleware/validation');
const { logger } = require('../utils/logger');
const db = require('../config/database');

// 导入控制器
const MenuController = require('../controllers/menuController');
const OrderController = require('../controllers/orderController');
const CouponController = require('../controllers/couponController');
const UserController = require('../controllers/userController');
const FileUploadUtil = require('../utils/fileUpload');
const Order = require('../models/Order');
const pointsService = require('../services/pointsService');
const Coupon = require('../models/Coupon');
const User = require('../models/User');

// 所有管理员路由都需要认证和管理员权限
router.use(authenticateToken);
router.use(requireAdmin);

// ==================== 用户管理 ====================

// 获取用户统计数据
router.get('/users/statistics', UserController.getAllUserStats);

// ==================== 仪表板统计 ====================

// 获取仪表板统计数据
router.get('/dashboard/stats', async (req, res) => {
  try {
    const { start_date, end_date } = req.query;
    const start = start_date ? new Date(start_date) : new Date(Date.now() - 6 * 86400000);
    const end = end_date ? new Date(end_date) : new Date();
    end.setHours(23, 59, 59, 999);
  
    const userTotal = await User.count();
    const orderTotal = await Order.count({ start_date, end_date });
  
    // 热销菜品、优惠券等统计
    const [topDishes, couponStats] = await Promise.all([
      Order.getTopDishes({ start_date, end_date, limit: 5 }).catch(() => []),
      Coupon.getStats({ start_date, end_date }).catch(() => ({ total: 0, used: 0 }))
    ]);
  
    // 订单、收入趋势（不使用任何mock填充）
    const ms = end - start;
    const isHourly = ms <= 2 * 86400000;
    const buckets = [];
    const pad = n => (n < 10 ? '0' + n : '' + n);
    const makeBucketKey = (d) => {
      const y = d.getFullYear();
      const m = pad(d.getMonth() + 1);
      const da = pad(d.getDate());
      if (isHourly) {
        const h = pad(d.getHours());
        return `${y}-${m}-${da} ${h}:00`;
      }
      return `${y}-${m}-${da}`;
    };
  
    const cursor = new Date(start);
    while (cursor <= end) {
      buckets.push(makeBucketKey(cursor));
      if (isHourly) cursor.setHours(cursor.getHours() + 1);
      else cursor.setDate(cursor.getDate() + 1);
    }
  
    const trendInit = Object.fromEntries(buckets.map(k => [k, { order_count: 0, revenue: 0 }]));
  
    const orders = await Order.findAll({ start_date, end_date, page: 1, limit: 10000, sort_by: 'created_at', sort_order: 'ASC' }).catch(() => []);
    for (const o of orders) {
      if (String(o.status) !== 'completed') continue;
      const createdAt = o.created_at ? new Date(o.created_at) : null;
      if (!createdAt || isNaN(createdAt)) continue;
      const key = makeBucketKey(createdAt);
      if (!trendInit[key]) continue;
      trendInit[key].order_count += 1;
      const amount = Number(o.total_amount || 0) || 0;
      trendInit[key].revenue += amount;
    }
  
    const orderTrend = buckets.map(b => ({ time: b, count: trendInit[b].order_count }));
    const revenueTrend = buckets.map(b => ({ time: b, amount: Number(trendInit[b].revenue.toFixed(2)) }));
  
    return res.json({ success: true, data: {
      userTotal,
      orderTotal,
      topDishes,
      couponStats,
      orderTrend,
      revenueTrend,
      bucketType: isHourly ? 'hour' : 'day'
    }});
  } catch (error) {
    logger.error('获取dashboard统计失败:', error);
    res.status(500).json({ success: false, message: '获取dashboard统计失败', error: error.message });
  }
});

// 获取最近订单
router.get('/dashboard/recent-orders', async (req, res) => {
  try {
    const recentOrders = [
      {
        id: 1,
        orderNumber: 'ORD-2024-001',
        customer: { name: '张三' },
        amount: 128.50,
        status: 'completed',
        time: new Date(Date.now() - 1000 * 60 * 30) // 30分钟前
      },
      {
        id: 2,
        orderNumber: 'ORD-2024-002',
        customer: { name: '李四' },
        amount: 89.00,
        status: 'pending',
        time: new Date(Date.now() - 1000 * 60 * 45) // 45分钟前
      },
      {
        id: 3,
        orderNumber: 'ORD-2024-003',
        customer: { name: '王五' },
        amount: 156.80,
        status: 'processing',
        time: new Date(Date.now() - 1000 * 60 * 60) // 1小时前
      }
    ];
    
    res.json(recentOrders);
  } catch (error) {
    logger.error('获取最近订单失败:', error);
    res.status(500).json({ error: '获取最近订单失败' });
  }
});

// 获取收入趋势
router.get('/dashboard/revenue-trends', async (req, res) => {
  try {
    const revenueTrends = [
      { date: '2024-01-01', revenue: 1200 },
      { date: '2024-01-02', revenue: 1350 },
      { date: '2024-01-03', revenue: 980 },
      { date: '2024-01-04', revenue: 1580 },
      { date: '2024-01-05', revenue: 1420 },
      { date: '2024-01-06', revenue: 1680 },
      { date: '2024-01-07', revenue: 1950 }
    ];
    
    res.json(revenueTrends);
  } catch (error) {
    logger.error('获取收入趋势失败:', error);
    res.status(500).json({ error: '获取收入趋势失败' });
  }
});

// 获取分类分布
router.get('/dashboard/category-distribution', async (req, res) => {
  try {
    const categoryData = [
      { name: '主食', value: 35, color: '#8884d8' },
      { name: '饮品', value: 25, color: '#82ca9d' },
      { name: '小食', value: 20, color: '#ffc658' },
      { name: '甜品', value: 15, color: '#ff7c7c' },
      { name: '其他', value: 5, color: '#8dd1e1' }
    ];
    
    res.json(categoryData);
  } catch (error) {
    logger.error('获取分类分布失败:', error);
    res.status(500).json({ error: '获取分类分布失败' });
  }
});

// 获取实时数据
router.get('/dashboard/realtime', async (req, res) => {
  try {
    // 获取今日实时数据
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const [todayOrders, activeUsers, pendingOrders] = await Promise.all([
      // 今日订单数
      OrderController.getTodayOrderCount(),
      // 活跃用户数（最近24小时登录）
      UserController.getActiveUserCount(),
      // 待处理订单数
      OrderController.getPendingOrderCount()
    ]);

    res.json({
      success: true,
      data: {
        todayOrders,
        activeUsers,
        pendingOrders,
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    logger.error('获取实时数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取实时数据失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

// ==================== 社交媒体管理 ====================

// 获取社交媒体统计数据
router.get('/social-media/stats', async (req, res) => {
  try {
    // 模拟社交媒体统计数据
    const stats = {
      totalReviews: 1250,
      averageRating: 4.6,
      positiveReviews: 1050,
      negativeReviews: 200,
      platforms: {
        wechat: { reviews: 450, rating: 4.7 },
        weibo: { reviews: 380, rating: 4.5 },
        dianping: { reviews: 420, rating: 4.6 }
      },
      recentReviews: [
        {
          id: 1,
          platform: 'wechat',
          user: '用户A',
          rating: 5,
          comment: '菜品很棒，服务很好！',
          date: new Date().toISOString()
        },
        {
          id: 2,
          platform: 'dianping',
          user: '用户B',
          rating: 4,
          comment: '环境不错，价格合理',
          date: new Date(Date.now() - 86400000).toISOString()
        }
      ]
    };
    
    res.json({ success: true, data: stats });
  } catch (error) {
    logger.error('获取社交媒体统计失败:', error);
    res.status(500).json({ success: false, message: '获取社交媒体统计失败', error: error.message });
  }
});

// ==================== 营销活动管理 ====================

// 获取营销活动统计数据
router.get('/marketing/stats', async (req, res) => {
  try {
    // 模拟营销活动统计数据
    const stats = {
      activeCampaigns: 5,
      totalCampaigns: 25,
      totalReach: 15000,
      totalConversions: 1200,
      conversionRate: 8.0,
      campaigns: [
        {
          id: 1,
          name: '春季特惠活动',
          type: 'discount',
          status: 'active',
          startDate: '2024-03-01',
          endDate: '2024-03-31',
          reach: 5000,
          conversions: 400,
          conversionRate: 8.0
        },
        {
          id: 2,
          name: '新品推广',
          type: 'promotion',
          status: 'active',
          startDate: '2024-03-15',
          endDate: '2024-04-15',
          reach: 3000,
          conversions: 250,
          conversionRate: 8.3
        }
      ],
      recentActivity: [
        {
          id: 1,
          action: '创建活动',
          campaign: '春季特惠活动',
          date: new Date().toISOString()
        },
        {
          id: 2,
          action: '更新活动',
          campaign: '新品推广',
          date: new Date(Date.now() - 3600000).toISOString()
        }
      ]
    };
    
    res.json({ success: true, data: stats });
  } catch (error) {
    logger.error('获取营销活动统计失败:', error);
    res.status(500).json({ success: false, message: '获取营销活动统计失败', error: error.message });
  }
});

// ==================== 库存管理 ====================

// 获取库存统计数据
router.get('/inventory/stats', async (req, res) => {
  try {
    // 模拟库存统计数据
    const stats = {
      totalItems: 150,
      lowStockItems: 12,
      outOfStockItems: 3,
      totalValue: 25000,
      categories: [
        { name: '主菜', items: 45, value: 12000 },
        { name: '小菜', items: 35, value: 5000 },
        { name: '饮品', items: 25, value: 3000 },
        { name: '甜品', items: 20, value: 2500 },
        { name: '其他', items: 25, value: 2500 }
      ],
      lowStockAlerts: [
        {
          id: 1,
          name: '宫保鸡丁',
          category: '主菜',
          currentStock: 5,
          minStock: 10,
          status: 'low'
        },
        {
          id: 2,
          name: '可乐',
          category: '饮品',
          currentStock: 0,
          minStock: 20,
          status: 'out'
        }
      ],
      recentMovements: [
        {
          id: 1,
          item: '宫保鸡丁',
          type: 'out',
          quantity: 3,
          date: new Date().toISOString()
        },
        {
          id: 2,
          item: '可乐',
          type: 'in',
          quantity: 50,
          date: new Date(Date.now() - 3600000).toISOString()
        }
      ]
    };
    
    res.json({ success: true, data: stats });
  } catch (error) {
    logger.error('获取库存统计失败:', error);
    res.status(500).json({ success: false, message: '获取库存统计失败', error: error.message });
  }
});

// ==================== 用户管理 ====================

// 获取所有用户
router.get('/users', UserController.getAllUsers);

// 获取用户详情
router.get('/users/:id', UserController.getUserById);

// 更新用户状态
router.put('/users/:id/status', [
  body('is_active')
    .isBoolean()
    .withMessage('用户状态必须是布尔值'),
  handleValidationErrors
], UserController.updateUserStatus);

// 重置用户密码
router.post('/users/:id/reset-password', UserController.resetUserPassword);

// 删除用户
router.delete('/users/:id', UserController.deleteUser);

// 获取用户统计
// router.get('/users/statistics', UserController.getUserStatistics);

// ==================== 菜单管理 ====================

// 菜单分类管理
router.put('/menu/categories/sort', MenuController.sortCategories);
router.get('/menu/categories', MenuController.getCategories);
router.post('/menu/categories', MenuController.createCategory);
router.put('/menu/categories/:id', MenuController.updateCategory);
router.delete('/menu/categories/:id', MenuController.deleteCategory);

// 菜品管理
router.put('/menu/items/sort', MenuController.sortMenuItems);
router.get('/menu/items', MenuController.getMenuItems);
router.post('/menu/items', MenuController.createMenuItem);
router.put('/menu/items/:id', MenuController.updateMenuItem);
router.delete('/menu/items/:id', MenuController.deleteMenuItem);
router.put('/menu/items/:id/availability', MenuController.updateAvailability);
router.put('/menu/items/sort', MenuController.sortMenuItems);

// 重置菜单项自增ID
router.post('/reset-menu-items-id', MenuController.resetMenuItemIds);

// 菜品图片上传（单图）
const menuImageUpload = FileUploadUtil.createMenuImageUpload();
router.post('/menu/items/:id/image', menuImageUpload.single('image'), async (req, res) => {
  try {
    const { id } = req.params;
    if (!req.file) {
      return res.status(400).json({ success: false, message: '未检测到上传文件' });
    }
    // 保存文件到 uploads/menu-images，并生成 URL
    const result = await FileUploadUtil.processMenuImagesUpload([req.file], id);
    // processMenuImagesUpload 返回的是字符串URL数组，这里取第一项；兼容未来可能返回对象的情况
    const imageUrl = Array.isArray(result) ? (typeof result[0] === 'string' ? result[0] : result[0]?.url) : (result?.url || result);

    if (!imageUrl) {
      return res.status(500).json({ success: false, message: '生成图片URL失败' });
    }

    // 更新菜单项的 image_url 字段
    const updated = await require('../models/MenuItem').update(id, { image_url: imageUrl });

    return res.json({ success: true, data: { image_url: updated?.image_url || imageUrl }, message: '图片上传成功' });
  } catch (error) {
    logger.error('菜单图片上传失败:', error);
    return res.status(500).json({ success: false, message: '图片上传失败', error: error.message });
  }
});

// 菜品图片批量上传（多图，返回列表，不写库）
router.post('/menu/images/batch', menuImageUpload.array('images', 8), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({ success: false, message: '未检测到上传文件' });
    }
    const result = await FileUploadUtil.processMenuImagesUpload(req.files);
    return res.json({ success: true, data: result, message: '批量图片上传成功' });
  } catch (error) {
    logger.error('批量菜单图片上传失败:', error);
    return res.status(500).json({ success: false, message: '批量图片上传失败', error: error.message });
  }
});

// ==================== 订单管理 ====================

// 获取所有订单
router.get('/orders', OrderController.getAllOrders)

// 重要：在参数化路由之前，先声明更具体的静态路由，避免被 /orders/:id 抢占
// 获取订单统计
router.get('/orders/statistics', OrderController.getOrderStatistics)

// 获取热门菜品
router.get('/orders/popular-items', OrderController.getPopularItems)

// 获取订单详情（限制 id 为数字，避免 'statistics' 等被误匹配）
router.get('/orders/:id(\\d+)', OrderController.getOrderDetail)

// 更新订单状态
router.put('/orders/:id(\\d+)/status', OrderController.updateOrderStatus)

// 更新支付状态
router.put('/orders/:id(\\d+)/payment', OrderController.updatePaymentStatus)

// 获取类别销售
router.get('/orders/category-sales', OrderController.getCategorySales)
// 获取订单类型分布
router.get('/orders/type-distribution', OrderController.getOrderTypeDistribution)
// 获取付款方式分布
router.get('/orders/payment-distribution', OrderController.getPaymentMethodDistribution)
// 获取热门客户
router.get('/orders/top-customers', OrderController.getTopCustomers)
// 新增：订单类型与支付方式趋势
router.get('/orders/type-trend', OrderController.getOrderTypeTrend)
router.get('/orders/payment-trend', OrderController.getPaymentMethodTrend)

// ==================== 优惠券管理 ====================

// 获取所有优惠券
router.get('/coupons', CouponController.getAllCoupons);

// 创建优惠券
router.post('/coupons', CouponController.createCoupon);

// 更新优惠券
router.put('/coupons/:id', CouponController.updateCoupon);

// 删除优惠券
router.delete('/coupons/:id', CouponController.deleteCoupon);

// 批量发放优惠券
router.post('/coupons/batch-distribute', CouponController.batchDistributeCoupons);

// 获取优惠券统计
router.get('/coupons/statistics', CouponController.getCouponStatistics);

// ==================== 系统管理 ====================

// 获取系统信息
router.get('/system/info', (req, res) => {
  res.json({
    success: true,
    data: {
      version: process.env.npm_package_version || '1.0.0',
      nodeVersion: process.version,
      platform: process.platform,
      uptime: process.uptime(),
      memory: process.memoryUsage(),
      environment: process.env.NODE_ENV || 'development',
      timestamp: new Date().toISOString()
    }
  });
});

// 获取系统配置
router.get('/system/config', async (req, res) => {
  try {
    const config = {
      database: {
        host: process.env.DB_HOST || 'localhost',
        port: process.env.DB_PORT || 3306,
        name: process.env.DB_NAME || 'restaurant_db',
        maxConnections: 100
      },
      server: {
        port: process.env.PORT || 3000,
        environment: process.env.NODE_ENV || 'development',
        cors: {
          enabled: true,
          origins: ['http://localhost:3001', 'http://localhost:5173']
        }
      },
      features: {
        socialMediaIntegration: true,
        paymentGateway: true,
        emailNotifications: true,
        smsNotifications: false
      },
      security: {
        jwtExpiration: '24h',
        passwordMinLength: 6,
        maxLoginAttempts: 5
      }
    };
    
    res.json({ success: true, data: config });
  } catch (error) {
    logger.error('获取系统配置失败:', error);
    res.status(500).json({ success: false, message: '获取系统配置失败', error: error.message });
  }
});

// 获取系统备份
router.get('/system/backups', async (req, res) => {
  try {
    const backups = [
      {
        id: 1,
        name: 'backup_2024_03_15_daily.sql',
        type: 'database',
        size: '25.6 MB',
        created_at: '2024-03-15T02:00:00Z',
        status: 'completed'
      },
      {
        id: 2,
        name: 'backup_2024_03_14_daily.sql',
        type: 'database',
        size: '24.8 MB',
        created_at: '2024-03-14T02:00:00Z',
        status: 'completed'
      },
      {
        id: 3,
        name: 'backup_2024_03_13_daily.sql',
        type: 'database',
        size: '24.2 MB',
        created_at: '2024-03-13T02:00:00Z',
        status: 'completed'
      },
      {
        id: 4,
        name: 'files_backup_2024_03_15.tar.gz',
        type: 'files',
        size: '156.3 MB',
        created_at: '2024-03-15T03:00:00Z',
        status: 'completed'
      }
    ];
    
    res.json({ success: true, data: backups });
  } catch (error) {
    logger.error('获取系统备份失败:', error);
    res.status(500).json({ success: false, message: '获取系统备份失败', error: error.message });
  }
});

// 获取系统日志（简单实现）
router.get('/system/logs', (req, res) => {
  const { level = 'info', limit = 100 } = req.query;
  
  // 这里应该从日志文件或日志系统中读取
  // 暂时返回模拟数据
  res.json({
    success: true,
    data: {
      logs: [
        {
          timestamp: new Date().toISOString(),
          level: 'info',
          message: '系统正常运行',
          source: 'system'
        }
      ],
      total: 1,
      level,
      limit: parseInt(limit)
    }
  });
});

// 清理缓存
router.post('/system/clear-cache', (req, res) => {
  try {
    // 这里可以实现缓存清理逻辑
    res.json({ success: true, message: '缓存清理成功' });
  } catch (error) {
    logger.error('清理缓存失败:', error);
    res.status(500).json({ success: false, message: '清理缓存失败', error: error.message });
  }
});

// ==================== 数据导出（待实现示例） ====================

// 导出用户数据（CSV）
router.get('/export/users', async (req, res) => {
  res.json({ success: true, message: '导出功能开发中' });
});

// 导出订单数据（CSV）
router.get('/export/orders', async (req, res) => {
  res.json({ success: true, message: '导出功能开发中' });
});

// ==================== 会员/积分管理 ====================
// 手工调整积分
router.post('/users/:userId/points/adjust', async (req, res) => {
  try {
    const userId = req.params.userId;
    const { delta, reason } = req.body || {};
    const amt = Math.floor(Number(delta || 0));
    if (!amt || amt === 0) {
      return res.status(400).json({ success: false, message: 'delta必须为非零整数' });
    }
    const result = amt > 0
      ? await pointsService.addPoints(userId, amt, { reason: reason || '管理员加分', source: 'admin_adjust', type: 'adjust', expiresInYears: 1 })
      : await pointsService.deductPoints(userId, Math.abs(amt), { reason: reason || '管理员扣分', source: 'admin_adjust', type: 'adjust' });
    return res.json({ success: true, message: '积分调整成功', data: result });
  } catch (e) {
    logger.error('积分调整失败:', e);
    res.status(500).json({ success: false, message: '积分调整失败' });
  }
});

// 触发过期作废扫描（手动）
router.post('/loyalty/expire', async (req, res) => {
  try {
    const { limit = 1000 } = req.body || {};
    const result = await pointsService.expireDuePoints(Number(limit));
    res.json({ success: true, message: '过期处理已执行', data: result });
  } catch (e) {
    logger.error('过期处理失败:', e);
    res.status(500).json({ success: false, message: '过期处理失败' });
  }
});

module.exports = router;